package club.yuit.desktop.ui.topics.cut;

import com.formdev.flatlaf.extras.components.FlatTriStateCheckBox;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author: yuit
 * @date: 2023/12/13 14:42
 */
@Slf4j
public class CUTTableHeaderCellRenderer implements TableCellRenderer {

    public final static FlatTriStateCheckBox CHECK_BOX = new FlatTriStateCheckBox();

    static {
        CHECK_BOX.setHorizontalAlignment(SwingConstants.CENTER);
        CHECK_BOX.setState(FlatTriStateCheckBox.State.UNSELECTED);
    }


    public CUTTableHeaderCellRenderer(JTable table) {
        JTableHeader tableHeader = table.getTableHeader();
        CUTopicBrokerTableModel model = (CUTopicBrokerTableModel) table.getModel();
        tableHeader.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int button = e.getButton();
                // 鼠标左键
                if (button==MouseEvent.BUTTON1){
                    // 获取点击的列index
                    int index = tableHeader.columnAtPoint(e.getPoint());
                    if (index == 0) {
                        boolean selected = !CHECK_BOX.isSelected();
                        CHECK_BOX.setSelected(selected);
                        log.debug("box status {}", selected);

                        model.allRowSelected(selected);

                        CHECK_BOX.updateUI();
                        // 跟新表头组件
                        tableHeader.repaint();

                    }
                }

            }
        });

    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row, int column) {
        JComponent component = createComponent(value, column);
        JTableHeader tableHeader = table.getTableHeader();
        component.setForeground(tableHeader.getForeground());
        component.setBackground(tableHeader.getBackground());
        component.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        return component;
    }


    private JComponent createCheckBox() {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
        panel.add(CHECK_BOX);
        return panel;
    }


    private JComponent createLabel(Object v) {
        JLabel l = new JLabel(v.toString());
        l.setHorizontalAlignment(SwingConstants.CENTER);
        return l;
    }

    public JComponent createComponent(Object v, int column) {
        return column == 0 ? createCheckBox() : createLabel(v);
    }


}
